<template>
    <div class="user-info">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>个人中心</span>
          </div>
        </template>
        
        <el-form ref="form" :model="userForm" label-width="100px" :rules="rules">
          <el-form-item label="用户ID">
            <el-input v-model="userForm.userId" disabled />
          </el-form-item>
          
          <el-form-item label="用户名">
            <el-input v-model="userForm.userName" disabled />
          </el-form-item>
          
          <el-form-item label="邮箱">
            <el-input v-model="userForm.userEmail" disabled />
          </el-form-item>
          
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="userForm.mobile" placeholder="请输入手机号" />
          </el-form-item>
    
          <el-form-item label="状态">
            <el-tag :type="stateTagType">
              {{ stateMap[userForm.state] }}
            </el-tag>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSubmit" v-has="'userinfo-save'">保存</el-button>
            <el-button type="primary" @click="showChangePasswordDialog" v-has="'userinfo-change-password'">修改密码</el-button>
          </el-form-item>
        </el-form>

        <el-dialog
          title="修改密码"
          v-model="isChangePasswordDialogVisible"
          width="30%"
          @close="resetPasswordForm"
        >
          <!-- 狗屎bug，ref不能和model同名 -->
          <el-form ref="passwordData" :model="passwordForm" label-width="100px" :rules="passwordRules">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" @input="console.log(passwordForm.oldPassword)"/>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" />
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmNewPassword">
              <el-input v-model="passwordForm.confirmNewPassword" type="password" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="isChangePasswordDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleChangePassword">确定</el-button>
          </template>
        </el-dialog>
      </el-card>
    </div>
</template>
  
<script>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

export default {
  name: 'UserInfo',
  setup() {
    const { proxy } = getCurrentInstance()
    const store = useStore()
    const userForm = reactive({
      userId: '',
      userName: '',
      userEmail: '',
      mobile: '',
      job: '',
      state: 1
    })
    
    // 修改密码相关数据
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmNewPassword: ''
    })
    const isChangePasswordDialogVisible = ref(false)

    const stateMap = {
      1: '正常',
      2: '禁用',
      3: '待审核'
    }

    const stateTagType = computed(() => {
      const types = {
        1: 'success',
        2: 'danger',
        3: 'warning'
      }
      return types[userForm.state] || ''
    })
    
    const rules = reactive({
      mobile: [
        {
          pattern: /1[3-9]\d{9}/, 
          message: '请输入正确的手机号格式', 
          trigger: 'blur' 
        }
      ]
    })

    const passwordRules = reactive({
      oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '新密码长度至少为6位', trigger: 'blur' }
      ],
      confirmNewPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { validator: (rule, value, callback) => {
          if (value!== passwordForm.newPassword) {
            callback(new Error('两次输入的新密码不一致'));
          } else {
            callback();
          }
        }, trigger: 'blur' }
      ]
    })
    
    // 获取当前用户信息
    const getUserInfo = async () => {
    try {
        // 假设 api 中新增了获取当前用户信息的接口
        const res = await proxy.$api.getCurrentUserInfo(); 
        // 将获取到的信息赋值给 userForm
        Object.assign(userForm, res);
        // 处理用户信息
    } catch (error) {
        // 错误处理
        ElMessage.error(error.message || '获取用户信息失败');
    }
    }
    // 更新个人信息
    const updateUserInfo = async (data) => {
        try {
          const res = await proxy.$api.updateUserInfo({
            job: data.job,
            mobile: data.mobile
          });
          // 处理成功响应
        } catch (error) {
          // 错误处理
          ElMessage.error(error.message || '修改失败');
        }
    }
    // 保存修改
    const handleSubmit = async () => {
      try {
        await updateUserInfo(userForm);
        ElMessage.success('修改成功')
      } catch (error) {
        ElMessage.error(error.message || '修改失败')
      }
    }

    // 新增显示修改密码对话框方法
    const showChangePasswordDialog = () => {
      console.log('showChangePasswordDialog 函数被调用');
      isChangePasswordDialogVisible.value = true;
      console.log('isChangePasswordDialogVisible 的值为:', isChangePasswordDialogVisible.value);
      resetPasswordForm();
    }
    // 新增重置密码表单方法
    const resetPasswordForm = () => {
      passwordForm.oldPassword = '';
      passwordForm.newPassword = '';
      passwordForm.confirmNewPassword = '';
    }
    // 新增修改密码方法
    const handleChangePassword = async () => {
      try {
        // await proxy.$api.changePassword(passwordForm);
        console.log('提交的数据:', passwordForm); // 调试确认数据
        const res = await proxy.$api.changePassword({
          oldPassword: passwordForm.oldPassword, // 明确传递字段
          newPassword: passwordForm.newPassword,
          confirmNewPassword: passwordForm.confirmNewPassword
        });
        ElMessage.success('密码修改成功');
        isChangePasswordDialogVisible.value = false;
        resetPasswordForm();
      } catch (error) {
        ElMessage.error(error.message || '密码修改失败');
      }
    } 

    onMounted(() => {
      getUserInfo()
    })
    
    return {
      userForm,
      rules,
      stateMap,
      stateTagType,
      handleSubmit,
      updateUserInfo,
      isChangePasswordDialogVisible,
      passwordForm,
      passwordRules,
      showChangePasswordDialog,
      handleChangePassword,
      resetPasswordForm
    }
  }
}
</script>